const cloud = require('wx-server-sdk');
cloud.init();

exports.main = async (event) => {
  const db = cloud.database();
  let res = null;

  if (event.action === 'start') {
    const course = await db.collection('course').doc(event._id).get();
    let leaveStudents = course.data.leaveStudents ? [...course.data.leaveStudents] : []
    res = await db.collection('course').doc(event._id).update({
      data: {
        active: true,
        method: event.method,
        verifyCode: event.verifyCode,
        location: event.location,
        check: db.command.push({
          date: new Date(),
          students: [],
          leaveStudents: leaveStudents
        }),
        leaveStudents: []
      }
    });
  }

  if (event.action === 'stop') {
    res = await db.collection('course').doc(event._id).update({
      data: {
        active: false
      }
    });
  }

  return res;
};
